import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElLoading } from 'element-plus';
import { ElMessage } from 'element-plus';

let loading: any;

const startLoading = () => {
	interface Options {
		lock: boolean;
		text: string;
		background: string;
	}

	const options: Options = {
		lock: true,
		text: '加载中...',
		background: 'rgba(0,0,0,0.7)',
	};
	loading = ElLoading.service(options);
};

const endLoading = () => {
	loading.close();
};

//根路径
axios.defaults.baseURL = 'http://117.72.38.229/';

//请求拦截
axios.interceptors.request.use((config: AxiosRequestConfig) => {
	config.headers.Authorization = window.sessionStorage.getItem('token');
	// console.log(config)

	//加载
	// startLoading()

	return config;
});

//响应拦截
axios.interceptors.response.use(
	(response: AxiosResponse<any>) => {
		//结束loading
		// endLoading();
		//判断token是否过期或者重复登陆，如果是就直接跳转回登陆页
		const code = response.data.code;
		if (code == 401) {
			ElMessage.error(response.data.msg);
			window.location.href = '/login';

			return;
		} else {
			return response;
		}
	},
	(error) => {
		// //结束loading
		// endLoading();
		//错误提醒

		switch (error.response.status) {
			case 403:
				ElMessage.error('拒绝访问(403)');
				break;
			case 404:
				ElMessage.error('请求出错(404)');
				break;
			case 408:
				ElMessage.error('请求超时(408)');
				break;
			case 500:
				ElMessage.error('服务器内部错误(500)');
				break;
			case 501:
				ElMessage.error('服务未实现(501)');
				break;
			case 502:
				ElMessage.error('网络错误(502)');
				break;
		}
		return Promise.reject(error);
	}
);

export default axios;
